import { createRouter, createWebHistory } from "vue-router";
import Login from "@/views/Login.vue";
import Layout from "@/views/Layout.vue";
import UserInfo from "@/views/user/UserInfo.vue";
import UserList from "@/views/user/UserList.vue";
import RestPassword from "@/views/user/RestPassword.vue";
import ApplicationList from "@/views/application/ApplicationList.vue";
import ApplicationReview from "@/views/application/ApplicationReview.vue";
import ApplicationForm from "@/views/application/ApplicationForm.vue";
import MyApplication from "@/views/application/MyApplication.vue";
import MyRegistration from "@/views/registration/MyRegistration.vue";
import StatisticsOverview from "@/views/statistics/StatisticsOverview.vue";
import BatchList from "@/views/batch/BatchList.vue";
import BatchEdit from "@/views/batch/BatchEdit.vue";
import StyleList from "@/views/clothingStyle/StyleList.vue";
import StyleAdd from "@/views/clothingStyle/StyleAdd.vue";
import AiChat from "@/views/ai/AiChat.vue";



// 定义路由关系
const routes = [
  { path: '/login', component: Login },  // 一级路由
  {
    path: '/',
    redirect: '/user/info',  // 重定向到个人中心（所有用户都有权限）
    component: Layout,
    // 子路由
    children: [
      { path: '/user/list', component: UserList },
      { path: '/user/info', component: UserInfo },
      { path: '/user/resetPassword', component: RestPassword },
      { path: '/application/list', component: ApplicationList },
      { path: '/application/applicationReview', component: ApplicationReview },
      { path: '/application/form', component: ApplicationForm },
      { path: '/application/myApplication', component: MyApplication },
      { path: '/registration/myRegistration', component: MyRegistration },
      { path: '/statistics/overview', component: StatisticsOverview },
      { path: '/batch/list', component: BatchList },
      { path: '/batch/edit/:id', component: BatchEdit },
      { path: '/clothingStyle/list', component: StyleList },
      { path: '/clothingStyle/add', component: StyleAdd },
      { path: '/ai/chat', component: AiChat }
    ]
  },
]

// 创建路由器
const router = createRouter({
  history: createWebHistory(), // 路由模式
  routes: routes
})

// 路由守卫 - 验证登录状态
router.beforeEach((to, from, next) => {
  // 从 localStorage 直接读取 token，避免循环依赖
  let token = null
  const userInfoData = localStorage.getItem('userInfo')
  if (userInfoData) {
    try {
      const userData = JSON.parse(userInfoData)
      token = userData.token
    } catch (e) {
      console.error('解析userInfo失败:', e)
    }
  }

  // 如果访问登录页
  if (to.path === '/login') {
    // 如果已经登录，重定向到个人中心
    if (token) {
      next('/user/info')
    } else {
      next() // 未登录，正常访问登录页
    }
  } else {
    // 访问其他页面，检查是否有token
    if (token) {
      next() // 有token，放行
    } else {
      next('/login') // 没有token，重定向到登录页
    }
  }
})

//导出暴露
export default router
